import React, { FC, memo, useEffect, useCallback, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { List, Button, WingBlank } from 'antd-mobile';
import { Link, useLocation, Location } from 'umi';
import { loadUser, loadLogout } from '@/stores/reducer/user';
import { RootState } from '@/interface';

import './index.less';

const User: FC = () => {
  const [btnLoading, setBtnLoading] = useState(false);
  const dispatch = useDispatch();
  const { query }: Location = useLocation();
  const { username, avatar, phone, sign } = useSelector(
    (state: RootState) => state.user,
  );

  useEffect(() => {
    dispatch(
      loadUser({
        id: query?.id,
      }),
    );
  }, []);

  const handleLogout = useCallback(async () => {
    setBtnLoading(true);
    await dispatch(loadLogout({}));
    setBtnLoading(false);
  }, [setBtnLoading]);

  return (
    <div className="user-page-wrap">
      <div className="info">
        <div className="set">
          <Link to="/user/edit">设置</Link>
        </div>
        <div className="user">
          <img
            alt="user"
            src={avatar || require('../../assets/defaultUser.jpg')}
          />
          <div className="name">{username}</div>
          <div className="tel">{phone}</div>
          <div className="sign">{sign}</div>
        </div>
      </div>
      <div className="lists">
        <List>
          <List.Item arrow="horizontal">用户协议</List.Item>
          <List.Item arrow="horizontal">常见问题</List.Item>
          <List.Item arrow="horizontal">联系客服</List.Item>
        </List>
      </div>
      <div className="footer">
        <WingBlank>
          <Button type="warning" onClick={handleLogout} loading={btnLoading}>
            退出登录
          </Button>
        </WingBlank>
      </div>
    </div>
  );
};

export default memo(User);
